package com.zn.kjj.util;


import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * . 工具类
 * @author w15579
 *
 */
public class Tools {
    private static Pattern pattern = Pattern.compile("^(-)?[0-9]*$");

    /**
     * @Title: getMD5
     * @Description: MD5生成类
     * @param str 待加密字符串
     * @return 返回MD5码
     * @since v1.0.0
     */
    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            return null;
        }
    }
    /**.
     * 获取UUID Tools.getInstance().getUuid()
     * @return uuid
     */
    public static final String getUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**.
     * 校验字符串是否为数字
     * @param str 待检测字符串
     * @return 返回是否数字
     */
    public  boolean isNumeric(String str) {
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    /**
     * @Title: getIpAddr
     * @Description: 获取IP地址
     * @param request 请求
     * @return 返回IP地址
     * @since v1.0.9
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    /**
     * 获取操作系统和浏览器信息
     * @param request 请求
     * @return 操作系统和浏览器信息
     */
    public static String getOsAndBrowserInfo(HttpServletRequest request){
        String  browserDetails  =   request.getHeader("User-Agent");
        String  userAgent       =   browserDetails;
        String  user            =   userAgent.toLowerCase();

        String os = "";
        String browser = "";

        //=================OS Info=======================
        if (userAgent.toLowerCase().indexOf("windows") >= 0 ) {
            os = "Windows";
        } else if(userAgent.toLowerCase().indexOf("mac") >= 0) {
            os = "Mac";
        } else if(userAgent.toLowerCase().indexOf("x11") >= 0) {
            os = "Unix";
        } else if(userAgent.toLowerCase().indexOf("android") >= 0) {
            os = "Android";
        } else if(userAgent.toLowerCase().indexOf("iphone") >= 0) {
            os = "IPhone";
        }else{
            os = "UnKnown, More-Info: "+userAgent;
        }
        //===============Browser===========================
        if (user.contains("edge")) {
            browser=(userAgent.substring(userAgent.indexOf("Edge")).split(" ")[0]).replace("/", "-");
        } else if (user.contains("msie")) {
            String substring=userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
            browser=substring.split(" ")[0].replace("MSIE", "IE")+"-"+substring.split(" ")[1];
        } else if (user.contains("safari") && user.contains("version")) {
            browser=(userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0]
                    + "-" +(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
        } else if ( user.contains("opr") || user.contains("opera")) {
            if(user.contains("opera")){
                browser=(userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split("/")[0]
                        +"-"+(userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
            }else if(user.contains("opr")){
                browser=((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-"))
                        .replace("OPR", "Opera");
            }

        } else if (user.contains("chrome")) {
            browser=(userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0]).replace("/", "-");
        } else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1)
                || (user.indexOf("mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1)
                || (user.indexOf("mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1) ) {
            browser = "Netscape-?";

        } else if (user.contains("firefox")) {
            browser=(userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-");
        } else if(user.contains("rv")) {
            String strIEVersion = (userAgent.substring(userAgent.indexOf("rv")).split(" ")[0]).replace("rv:", "-");
            browser="IE" + strIEVersion.substring(0,strIEVersion.length() - 1);
        } else {
            browser = "UnKnown, More-Info: "+userAgent;
        }

        return os +"-"+ browser ;
    }
    /**
     * .
     * @Title: main
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param args 参数说明
     * @since v1.0.0
     */
    public static void main(String[] args) {
        boolean blnFlag = true;
        Map<Object, Object> map = new HashMap<>();
        map.put("a", blnFlag);
        System.out.println(map.get("a").getClass());
        String str2 = getServIP();
        System.out.println(str2);
    }

    /**
     * 获取服务端IP
     * @Title: getServIP
     * @Description: 获取服务端IP
     * @return 参数说明
     * @since v1.0.0
     */
    @SuppressWarnings("rawtypes")
    public static String getServIP() {
        String ipStr = "";
        InetAddress ip = null;
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                //System.out.println(netInterface.getName());
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        System.out.println("本机的IP = " + ip.getHostAddress());
                    }
                    if (!ip.isLinkLocalAddress() && !ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                        if("".equals(ipStr)){
                            ipStr=ipStr+ip.toString().replaceAll("/", "");
                        }else{
                            ipStr=ipStr+"-"+ip.toString().replaceAll("/", "");
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipStr;
    }
}
